package com.itany.corejava.day12;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class TestJTable {

    private JFrame jf;
    private JTable jt;

    public TestJTable(List<User> users) {
        jf=new JFrame();

        // TableModel model=new MyTableModel(users);
        DefaultTableModel model=new DefaultTableModel();
        model.addColumn("id");
        model.addColumn("username");
        model.addColumn("age");
        for (User user : users) {
            Vector<String> rowData=new Vector<>();
            rowData.add(user.getId()+"");
            rowData.add(user.getUsername());
            rowData.add(user.getAge()+"");
            model.addRow(rowData);
        }

        jt=new JTable(model);
    }

    class MyTableModel extends AbstractTableModel {

        private List<User> users;

        public MyTableModel(List<User> users) {
            this.users = users;
        }

        @Override
        public int getRowCount() {
            return users.size();
        }

        @Override
        public int getColumnCount() {
            return 3;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            User user=users.get(rowIndex);
            if(columnIndex==0){
                return user.getId();
            }
            if(columnIndex==1){
                return user.getUsername();
            }
            if(columnIndex==2){
                return user.getAge();
            }
            return null;
        }

        @Override
        public String getColumnName(int column) {
            if(column==0){
                return "id";
            }
            if(column==1){
                return "username";
            }
            if(column==2){
                return "age";
            }
            return null;
        }
    }

    private void init(){
        JScrollPane jsp=new JScrollPane(jt);
        jf.add(jsp);
    }

    public void show(){
        init();
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        List<User> users=new ArrayList<>();

        users.add(new User(1,"aaa",23));
        users.add(new User(2,"bbb",26));
        users.add(new User(3,"ccc",21));
        users.add(new User(4,"ddd",22));
        users.add(new User(5,"eee",28));


        new TestJTable(users).show();
    }
}
